package cz.cvut.fit.mi_paa.knapsack;

import cz.cvut.fit.mi_paa.abs.Context;
import cz.cvut.fit.mi_paa.utils.StopWatch;

import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * User: milos
 * Date: 1.10.12
 * Time: 11:08
 * To change this template use File | Settings | File Templates.
 */
public class KnapsackContext extends Context {

    private KnapsackInstance instance;

    public KnapsackContext(FileWriter resultWriter, BufferedReader inputReader, StopWatch sw) {
        super(resultWriter,inputReader,sw);
    }

    public boolean nextInstance() throws IOException {
        String instanceString = inputReader.readLine();
        if(instanceString!=null) {
            String[] numbers = instanceString.split("\\s");
            Item[] items = getItems(numbers);
            this.instance = new KnapsackInstance(Integer.valueOf(numbers[0]),Integer.valueOf(numbers[2]),items);
            return true;
        } else {
            return false;
        }

    }

    public void close() throws IOException {
        resultWriter.close();
        inputReader.close();
    }

    private Item[] getItems(String[] numbers) {
        int arraySize = Integer.valueOf(numbers[1]);
        Item[] array = new Item[arraySize];
        for(int i=3;i<numbers.length;i=i+2) {
            int index = (i-3)/2;
            array[index] = new Item(Integer.valueOf(numbers[i]),Integer.valueOf(numbers[i+1]),index);
        }
        return array;
    }

    public KnapsackInstance getInstance() {
        return instance;
    }
}
